<template>
  <div
    class="min-h-screen bg-gradient-to-br from-amber-50 to-orange-100 flex items-center justify-center p-4 md:p-8"
  >
    <!-- 背景装饰元素 -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none">
      <div
        class="absolute -top-40 -right-40 w-96 h-96 bg-orange-200 rounded-full opacity-50 blur-3xl"
      ></div>
      <div
        class="absolute -bottom-40 -left-40 w-96 h-96 bg-amber-200 rounded-full opacity-50 blur-3xl"
      ></div>
    </div>

    <div
      class="w-full max-w-4xl flex flex-col md:flex-row bg-white rounded-2xl shadow-xl overflow-hidden relative z-10"
    >
      <!-- 左侧图片区域 -->
      <div class="w-full md:w-1/2 relative hidden md:block">
        <img
          src="https://picsum.photos/id/431/800/1000"
          alt="美食展示"
          class="absolute inset-0 w-full h-full object-cover"
        />
        <div
          class="absolute inset-0 bg-gradient-to-r from-orange-600/80 to-transparent flex items-end"
        >
          <div class="p-12 text-white">
            <h1 class="text-[clamp(2rem,4vw,3rem)] font-bold mb-2">美食汇</h1>
            <p class="text-xl opacity-90 mb-4">多餐厅点餐系统</p>
            <p class="max-w-md opacity-80">
              连接城市里的万千美食，为您提供便捷、安全、美味的点餐体验。
              无论是用户、商家还是管理员，都能在这里找到属于自己的价值。
            </p>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单区域 -->
      <div class="w-full md:w-1/2 p-8 md:p-12 flex flex-col justify-center">
        <!-- 移动端标题 -->
        <div class="md:hidden mb-8">
          <h1 class="text-3xl font-bold text-orange-600 mb-2">美食汇</h1>
          <p class="text-gray-600">多餐厅点餐系统</p>
        </div>

        <!-- 登录类型选择 -->
        <div class="mb-8">
          <div class="flex border-b border-gray-200">
            <button
              :class="[
                'flex-1 py-4 px-2 font-medium text-center transition-all',
                radio === 0
                  ? 'text-orange-600 border-b-2 border-orange-500'
                  : 'text-gray-500 hover:text-gray-700'
              ]"
              @click="radio = 0"
            >
              用户登录
            </button>
            <button
              :class="[
                'flex-1 py-4 px-2 font-medium text-center transition-all',
                radio === 1
                  ? 'text-orange-600 border-b-2 border-orange-500'
                  : 'text-gray-500 hover:text-gray-700'
              ]"
              @click="radio = 1"
            >
              商家登录
            </button>
            <button
              :class="[
                'flex-1 py-4 px-2 font-medium text-center transition-all',
                radio === 2
                  ? 'text-orange-600 border-b-2 border-orange-500'
                  : 'text-gray-500 hover:text-gray-700'
              ]"
              @click="radio = 2"
            >
              管理员登录
            </button>
          </div>
        </div>

        <!-- 表单 -->
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="90px"
          size="medium"
          class="space-y-6"
        >
          <!-- 用户名输入框 -->
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              :placeholder="nameTemp"
              class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-orange-400 focus:ring focus:ring-orange-200 focus:ring-opacity-50 transition-all outline-none"
              :class="{
                'border-red-500': $refs.formRef?.model.username && $refs.formRef?.errors.username
              }"
            />
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-orange-400 focus:ring focus:ring-orange-200 focus:ring-opacity-50 transition-all outline-none"
              :class="{
                'border-red-500': $refs.formRef?.model.password && $refs.formRef?.errors.password
              }"
            />
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item class="pt-3">
            <el-button
              type="primary"
              @click="onSubmit"
              :loading="isLoading"
              class="w-full py-3 bg-gradient-to-r from-orange-500 to-amber-500 text-white font-medium rounded-lg hover:shadow-lg hover:shadow-orange-200 transition-all transform hover:-translate-y-0.5 active:translate-y-0 focus:outline-none focus:ring-2 focus:ring-orange-400 focus:ring-opacity-50"
            >
              <span class="flex items-center justify-center">
                <i class="fa fa-sign-in mr-2"></i>
                登录
              </span>
            </el-button>
          </el-form-item>

          <!-- 注册链接 -->
          <div class="text-center text-sm text-gray-600">
            还没有账号？
            <el-button
              type="text"
              @click="register"
              class="text-orange-600 hover:text-orange-700 font-medium"
            >
              立即注册
            </el-button>
          </div>
        </el-form>

        <!-- 底部信息 -->
        <div class="mt-12 text-center text-xs text-gray-500">
          <p>© 2025 美食汇. 保留所有权利.</p>
          <p class="mt-1">隐私政策 | 服务条款 | 帮助中心</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormRules, FormInstance } from 'element-plus'
import { useTokenStore } from '@/stores/mytoken'
import { useUserNameStore } from '@/stores/userName'
import { useRestaurantTokenStore } from '@/stores/restaurant'
import { useRestaurantNameStore } from '@/stores/restaurantName'
import { useRestaurantIDStore } from '@/stores/restaurantID'
import { useManagerTokenStore } from '@/stores/managerToken'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ref, reactive } from 'vue'

// 单选框组件
let radio = ref(0)
let nameTemp = ref('用户ID')
function handleRadioChange(value: any) {
  console.log('选中了:', value)
  radio.value = value
  if (value === 1) {
    nameTemp.value = '商家ID'
  } else if (value === 0) {
    nameTemp.value = '用户ID'
  } else {
    nameTemp.value = '管理员ID'
  }
  isLoading.value = false
}

// 定义是否登录加载中
const isLoading = ref(false)
const formRef = ref<FormInstance>()
const router = useRouter()
const store = useTokenStore()
const userNamestore = useUserNameStore()
const storeRestaurant = useRestaurantTokenStore()
const storeRestaurantName = useRestaurantNameStore()
const storeResturantID = useRestaurantIDStore()
const storeManager = useManagerTokenStore()

// 表单数据
const form = reactive({
  username: '',
  password: ''
})

// 登录事件处理
const onSubmit = async () => {
  isLoading.value = true
  // 表单校验
  await formRef.value?.validate().catch((err) => {
    ElMessage.error('表单校验失败...')
    isLoading.value = false
    throw err
  })

  // 用户登录
  if (radio.value === 0) {
    axios({
      method: 'post',
      params: {
        username: form.username,
        password: form.password
      },
      url: 'http://localhost:8080/user/login'
    }).then(
      (res) => {
        const { data } = res
        if (data.code === 0) {
          store.saveToken(data.data)
          userNamestore.saveUesrName(form.username)
          isLoading.value = false
          ElMessage.success('登录成功!')
          router.push('/index')
        } else {
          ElMessage.error('账号或密码错误,请输入正确信息')
          isLoading.value = false
        }
      },
      (err) => {
        ElMessage.error('网络异常')
        console.log(err)
        isLoading.value = false
      }
    )
  }
  // 商家登录
  else if (radio.value === 1) {
    axios({
      method: 'post',
      params: {
        restaurantname: form.username,
        password: form.password
      },
      url: 'http://localhost:8080/restaurant/login'
    }).then((res) => {
      if (res.data.code === 0) {
        storeRestaurant.saveRestaurantToken(res.data.data)
        isLoading.value = false
        ElMessage.success('商家登录成功!')
        storeRestaurantName.saveRestaurantName(form.username)
        getRestaurantID(form.username)
        router.push('/AppLayout1')
      } else if (res.data.code === 1) {
        ElMessage.error('账号或密码错误,请输入正确信息')
        isLoading.value = false
      }
    })
  }
  // 管理员登录
  else {
    axios({
      method: 'post',
      params: {
        managename: form.username,
        password: form.password
      },
      url: 'http://localhost:8080/manage/login'
    }).then((res) => {
      if (res.data.code === 0) {
        storeManager.saveManagerToken(res.data.data)
        isLoading.value = false
        ElMessage.success('管理员登录成功')
        router.push('/layout')
      } else {
        ElMessage.error('账号或密码错误,请输入正确信息')
        isLoading.value = false
      }
    })
  }

  // 获取餐厅ID
  function getRestaurantID(name: any) {
    axios({
      method: 'post',
      url: '/restaurant/restaurantInfo',
      params: {
        restaurantname: name
      },
      headers: {
        'Content-Type': 'application/octet-stream',
        Authorization: window.localStorage.getItem('RestaurantToken')
      }
    }).then((res) => {
      const { data } = res
      storeResturantID.saveRestaurantID(data.data.restaurantid)
    })
  }
}

// 注册事件处理
const register = async () => {
  router.push('/register')
}

// 定义表单校验规则
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度需要6~18位', trigger: 'blur' }
  ]
})
</script>

<style scoped>
/* 自定义动画 */
@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.animate-float {
  animation: float 6s ease-in-out infinite;
}

/* 修复Element Plus组件和Tailwind的样式冲突 */
.el-input__inner {
  box-shadow: none !important;
}

/* 调整表单标签样式 */
.el-form-item__label {
  font-weight: 500;
  color: #333;
  padding-right: 10px;
}
</style>
